<?php
/**
 * label.php
 * User: yzm
 * Date: 2017/8/24
 */

class Label extends WebBase{
    /*
     * 标签列表
     */
    public function index() {
        global $_W,$_GPC;

        if ($_W['isajax']) {
            $where_sql = 'WHERE `uniacid`=:uniacid';
            $where[':uniacid'] = $_W['uniacid'];

            //搜索-标签名
            if ($_GPC['label_name']) {
                $where_sql .= " AND `label_name` LIKE :label_name ";
                $where[':label_name'] = '%' . $_GPC['label_name'] . '%';
            }

            $total = pdo_fetchcolumn("SELECT COUNT(*) FROM " . tablename('wherein_knowledge_label') . $where_sql, $where);

            $list = pdo_fetchall("SELECT * FROM ".tablename('wherein_knowledge_label') . $where_sql . " ORDER BY `label_id` DESC LIMIT " . $_GPC['offset'] . ", " . $_GPC['limit'], $where);
            foreach ($list as $key => $value) {
                $list[$key]['index'] = ($key+1) + ($_GPC['limit'] * ($_GPC['offset']/$_GPC['limit']));
            }

            $out['total'] = $total;
            $out['rows'] = $list;
            $this->outjson($out);
        }

        include $this->template('index');
    }

    /*
     * ajax-添加/修改标签库
     */
    public function operate() {
        global $_W,$_GPC;

        $data['uniacid'] = $_W['uniacid'];
        $data['label_name'] = trim($_GPC['label_name']);
        //检测label_name是否为空
        if (empty($_GPC['label_name'])) {
            $this->outjson(array('code' => 206, 'msg' => '请输入标签名'));
        }
        //检测label_name是否存在
        $res = $this->checkLabelName($_GPC['label_name']);
        if ($res['code'] == 0) {
            $this->outjson(array('code' => 206, 'msg' => '该标签名已经存在'));
        }
        //检测label_name是否超过8个字
        if (mb_strlen($_GPC['label_name']) > 24) {
            $this->outjson(array('code' => 206, 'msg' => '标签过长,不能超过8个汉字'));
        }

        if (empty($_GPC['label_id'])) {
            /***添加***/

            if (pdo_insert('wherein_knowledge_label', $data)) {
                $out['code'] = 200;
                $out['msg'] = '添加标签成功';
            } else {
                $out['code'] = 304;
                $out['msg'] = '添加标签失败';
            }
        } else {
            /***修改***/

            if(pdo_update('wherein_knowledge_label',$data,array('label_id' => $_GPC['label_id'], 'uniacid'=>$_W['uniacid']))){
                $out['code'] = 200;
                $out['msg'] = '修改标签成功';
            }else{
                $out['code'] = 304;
                $out['msg'] = '修改标签失败';
            }
        }
        $this->outjson($out);
    }

    /*
     * ajax-获取标签
     */
    public function getLabel() {
        global $_GPC;
        if (!empty($_GPC['label_id'])) {
            $label_item = pdo_get('wherein_knowledge_label', array('label_id' => $_GPC['label_id']), array('label_id', 'label_name'));
            $out['code'] = 200;
            $out['msg'] = '获取成功';
            $out['label'] = array(
                'label_id' => $label_item['label_id'],
                'label_name' => $label_item['label_name'],
            );
        } else {
            $out['code'] = 400;
            $out['msg'] = '获取失败';
            $out['label'] = array();
        }
        $this->outjson($out);
    }

    /*
     * ajax-删除标签
     */
    public function del() {
        global $_W,$_GPC;

        if ($_W['isajax']) {
            if (pdo_delete('wherein_knowledge_label', array('label_id' => $_GPC['label_id']))) {
                $out['code'] = 1;
                $out['msg'] = '删除标签成功';
            } else {
                $out['code'] = 0;
                $out['msg'] = '删除标签失败';
            }
            $this->outjson($out);
        }
    }

    /*
     * 导入标签
     */
    public function excelLabel() {
        global $_W,$_GPC;

        if (!is_writable(ATTACHMENT_ROOT)) {
            message(ATTACHMENT_ROOT . '目录不可写, 请授权', '', 'error');
        }
        //检测是upload和PHPExcel文件夹是否存在
        if (!is_dir(UPLOAD_EXCEL)) {
            if (!mkdir(UPLOAD_EXCEL, 0777, true)) {
                message('创建目录失败', 'referer', 'error');
            }
        }

        if (checksubmit()) {
            if (!empty($_FILES['phpexcel']['name'])) {

                $tmp_file = $_FILES['phpexcel']['tmp_name'];
                $file_types = explode (".", $_FILES['phpexcel']['name']);
                //取得文件后缀
                $file_type = $file_types[count($file_types)-1];
                /*判别是不是.xls文件，判别是不是excel文件*/
                if (!in_array(strtolower($file_type), array('xls', 'xlsx'))) {
                    message('不是Excel文件，重新上传', 'refresh', 'error');
                }
                /*设置上传路径*/
                $save_path = UPLOAD_EXCEL;
                if (!is_dir($save_path)) {
                    message('没有找到可上传的路径', 'refresh', 'error');
                }
                /*以时间来命名上传的文件*/
                $str = 'l'.date('Ymdhis').mt_rand('100', '999');
                $file_name = $str . '.' . $file_type;
                //上传文件的路径
                $file_path = $save_path . $file_name;
                /*是否上传成功*/
                if (!copy($tmp_file, $file_path)) {
                    message('上传失败', 'refresh', 'error');
                }

                /* 处理 */
                require IA_ROOT . '/framework/library/phpexcel/PHPExcel.php';

                $objReader = PHPExcel_IOFactory::createReader('Excel5');
                $objExcel = $objReader->load($file_path);
                $sheet = $objExcel->getSheet(0);
                $highestRow = $sheet->getHighestRow();//总行数
                if ($highestRow == 1) {
                    unlink($file_path);//删除导入的excel表
                    message('请在Excel表里添加标签名', 'refresh', 'error');
                }
                $allData = $objExcel->getActiveSheet()->toArray();
                $headerRow = $allData[0];
                $headerRow[1] = '错误原因';

                //$success_import 导入成功数量 $fail_import 导入失败数量
                $success_import = $fail_import = 0;
                $data = array();
                $err_list = array();//错误的数据
                $err_list[] = $headerRow;
                for ($i = 2;$i <= $highestRow;$i++) {
                    $error = array();
                    //判断每一行里的标签名在标签表里是否存在,存在则取id,不存在则新建标签
                    $label_name = $objExcel->getActiveSheet()->getCell("A".$i)->getValue();
                    if (utf8_strlen($label_name) > 8) {
                        //如果大于8个字, 则标出错误信息
                        $error[] = '标签最多8个字';
                    } else {
                        if (pdo_getcolumn('wherein_knowledge_label', array('uniacid' => $_W['uniacid'], 'label_name' => $label_name), 'label_id')) {
                            //数据已存在
                            $error[] = '标签已存在';
                            $fail_import++;
                        } else {
                            if (!empty($label_name)) {
                                $data[] = $label_name;
                            } else {
                                $error[] = '标签名不为空';
                                $fail_import++;
                            }
                        }
                    }
                    if (!empty($error)) {
                        $err_list[] = array(
                            $label_name,
                            implode(',', $error)
                        );
                    }
                }
                //错误的条数 > 0 说明有错误数据
                $count_err = count($err_list) - 1;
                if ($count_err > 0) {
                    cache_clean('label_upload_list');
                    cache_write('label_upload_list', $err_list);
                }
                if (!empty($data)) {
                    $sql = "INSERT INTO " . tablename('wherein_knowledge_label') . " (`uniacid`,`label_name`,`update_time`,`author`) VALUES ";
                    $i = 0;
                    $count_data = count($data);
                    foreach ($data as $key => $value) {
                        if ($i < $count_data) {
                            $sql .= "(";
                            $sql .= "'". $_W['uniacid'] . "', '" . $value . "', '" . date('Y-m-d H:i:s', $_W['timestamp']) . "', 'admin'";
                            $sql .= "),";
                        }
                        $i++;
                        $success_import++;
                    }
                    $sql = rtrim($sql, ',');
                    if (pdo_query($sql)) {
                        unlink($file_path);//删除导入的excel表
                        message('导入成功', $this->createWebUrl('label',array('act' => 'excelLabel','step' => 3, 's' => $success_import, 'f' => $count_err)), 'success');
                    } else {
                        message('写入数据库失败', 'refresh', 'error');
                    }
                } else {
                    message('没有可导入的数据', $this->createWebUrl('label',array('act' => 'excelLabel','step' => 3, 's' => 0, 'f' => $count_err)), 'error');
                }
            } else {
                message('请选择要上传的文件', 'refresh', 'error');
            }
        }
        include $this->template('excelLabel');
    }

    /*
     * 检测标签名是否存在
     * @param string $name 标签名
     */
    public function checkLabelName($name) {
        global $_W;
        if (empty($name)) {
            return array('code' => 0, 'msg' => '参数不全');
        }
        $res = pdo_getcolumn('wherein_knowledge_label', array('uniacid' => $_W['uniacid'], 'label_name' => trim($name)), 'label_id');
        return $res ? array('code' => 0, 'msg' => '该类别已存在') : array('code' => 1);
    }

    /*
         * 导出失败问题
         */
    public function downFailFile() {
        $data = cache_load('label_upload_list');
        //对数据进行检验
        if(empty($data) || !is_array($data)){
            message('没有失败的数据可下载', 'referer', 'error');
        }
        $fileName = '导出失败数据表_' . date('Y_m_d', time()) . '.xls';
        //创建PHPExcel对象，注意，不能少了
        /* 处理 */
        require IA_ROOT . '/framework/library/phpexcel/PHPExcel.php';
        $objPHPExcel = new PHPExcel();
        $objProps = $objPHPExcel->getProperties();

        $objPHPExcel->getActiveSheet()->setTitle($fileName);

        $column = 1;
        $objActSheet = $objPHPExcel->getActiveSheet();
        foreach($data as $key => $rows){ //行写入
            $span = ord("A");
            foreach($rows as $keyName=>$value){// 列写入
                if($span<=90){
                    $j = chr($span);
                }else{
                    $j = chr($span-26);
                }
                $objActSheet->setCellValue($j.$column, $value);
                $span++;
            }
            $column++;
        }

        $fileName = iconv("utf-8", "gb2312", $fileName);
        //重命名表
        //设置活动单指数到第一个表,所以Excel打开这是第一个表
        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output'); //文件通过浏览器下载
        cache_delete('label_upload_list');
        exit;
    }
}